package org.zhuzx.util.spring;

import java.lang.reflect.Field;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * BeanPostProcessor的实现，用于替换bean中定义的属性。
 * @author zhuzx 2018年08月23日
 */
public class ReplaceBeanPropertyProcessor extends ReplaceBeanPropertyConfiguration
		implements BeanPostProcessor {
	
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		boolean flag = (needReplacedBeanNames!=null && needReplacedBeanNames.contains(beanName))
				|| (needReplacedBeanPattern!=null && beanName.matches(needReplacedBeanPattern));
		if (flag) {
			try {
				Field field = bean.getClass().getDeclaredField(targetPropertyName);
				field.setAccessible(true);
				field.set(bean, replacementPropertyValue);
				System.out.println("bean[" + beanName + "]的" + targetPropertyName + "属性已替换");
				return bean;
			} catch (Exception e) {
				throw new RuntimeException("修改bean[" + beanName + "]"
						+ "的" + targetPropertyName + "属性时发生错误：" + e.getMessage(), e);
			}
		} else {
			return bean;
		}
	}

}